import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, setTokenTime,  removeToken, removeTokenTime, clearStorage } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userId:''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERUID: (state, userId) => {
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSION_ROUTES: (state, permission_routes) => {
    state.permission_routes = permission_routes
  }
}

const actions = {
  // user login  用户登录
  async login({ commit }, userInfo) {
    //解构出用户名和密码
    const { username, password,code } = userInfo
      //调用api/user里面的login方法
       let res = await login({ username: username.trim(), password: password ,code:code})
       if(res.code == 200){
        // window.location.href = "/"
        //把后端返回的token存到vuex中
        commit('SET_TOKEN', res.token)
        //把后端返回的token存到cookies里面
        setToken(res.token)
        //设置token过期时间
        setTokenTime(res.expireTime)
      }
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      //调用api/user里面的getInfo方法获取用户信息和权限信息
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('登陆验证失败，请尝试再次登录！')
        }
        const { permission_routes, name, avatar, introduction,id } = data
        //roles必须是一个数组
        if (!permission_routes || permission_routes.length <= 0) {
          // reject('用户初始化暂无权限！')
          permission_routes.push("tourist");
        }
        //把权限字段放到sessionStorage里面
        sessionStorage.setItem('permList',JSON.stringify(permission_routes))
        //把roles存到store里面
        // commit('SET_ROLES', roles)
        commit('SET_PERMISSION_ROUTES', permission_routes)
        commit('SET_USERUID', id)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  async logout({ commit, state, dispatch }) {
    let res = await logout(state.token);
    if (res && res.code == 200) {
      commit('SET_TOKEN', '')
      commit('SET_PERMISSION_ROUTES', [])
      //清空token
      removeToken();
      clearStorage();
      removeTokenTime();
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      //跳到登录
      window.location.href = "/login";
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
